package com.miqtech.master.wyrecorder.screenrecorder.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.constants.Constants;
import com.miqtech.master.wyrecorder.entity.CompleteTask;
import com.miqtech.master.wyrecorder.http.ResponseListener;
import com.miqtech.master.wyrecorder.utils.CloseUtil;
import com.miqtech.master.wyrecorder.utils.L;
import com.miqtech.master.wyrecorder.utils.ToastUtils;
import com.miqtech.master.wyrecorder.utils.Utils;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShareToFriendsUtil implements ResponseListener {

    private static boolean sIsWXAppInstalledAndSupported;
    private final int THUMB_SIZE = 90;
    private final int THUMB_SIZE_WIDTH = 90;
    private final int THUMB_SIZE_HEIGHT = 140;
    public Bitmap shareDownloadBmp;
    Map<String, String> params = new HashMap<>();
    private WeakReference<Context> mContextReference;
    private WeakReference<ExpertMorePopupWindow> popReference;
    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            ToastUtils.show("取消分享");
            if (popReference.get() != null) {
                popReference.get().dismiss();
            }
        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            ToastUtils.show("分享成功");
            if (popReference.get() != null) {
                popReference.get().dismiss();
            }
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            ToastUtils.show("分享失败" + e.errorMessage + " 错误码" + e.errorCode);
            if (popReference.get() != null) {
                popReference.get().dismiss();
            }
        }
    };
    /**
     * 微信
     */
    private IWXAPI api;
    /**
     * QQ
     */
    private Tencent mTencent;
    /**
     * 分享内容
     */
    private String shareTitle;
    private String shareContent;
    private String shareUrl;
    private String shareImgUrl;
    View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.llSina:
                    shareBySina(shareTitle, shareContent, shareUrl, shareImgUrl);
                    break;
                case R.id.llWeChat:
                    shareWyByWXFriend(shareTitle, shareContent, shareUrl, shareImgUrl, 0);
                    break;
                case R.id.llFriend:
                    shareWyByWXFriend(shareTitle, shareContent, shareUrl, shareImgUrl, 1);
                    break;
                case R.id.llQQ:
                    shareByQQ(shareTitle, shareContent, shareUrl, shareImgUrl);
                    break;
                /*case R.id.llQzone:
                    shareByQzone(shareTitle, shareContent, shareUrl, shareImgUrl);*/
            }
        }
    };
    private String shareBitmap;



    public ShareToFriendsUtil(Context _context, ExpertMorePopupWindow popwin) {
        this.mContextReference = new WeakReference<Context>(_context);
        this.popReference = new WeakReference<ExpertMorePopupWindow>(popwin);
//        // 快速授权时，请不要传入 SCOPE，否则可能会授权不成功
//        this.mSsoHandler = new SsoHandler((Activity) _context, getAuthInfo(_context));
    }

    private static boolean isWXAppInstalledAndSupported(Context context, IWXAPI api) {
        // LogOutput.d(TAG, "isWXAppInstalledAndSupported");
        sIsWXAppInstalledAndSupported = api.isWXAppInstalled() && api.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    public Tencent getmTencent(Context context) {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APP_ID, context);
        }
        return mTencent;
    }

    /**
     * 设置分享配置
     *
     * @param shareTitle   标题
     * @param shareContent 内容
     * @param shareUrl     链接
     * @param shareImgUrl  图片地址
     */
    public void setShareConfiguration(String shareTitle, String shareContent, String shareUrl, String shareImgUrl) {
        this.shareTitle = shareTitle;
        this.shareContent = shareContent;
        this.shareUrl = shareUrl;
        this.shareImgUrl = shareImgUrl;
    }

    /**
     * 显示弹框
     */
    public void setPopuwShow() {
        if (popReference.get() != null) {
            popReference.get().show();
        }
    }

    /*qq空间分享*/
    public void shareByQzone(String shareTitle, String shareContent, String shareUrl, String shareImgUrl) {
        Bundle params = new Bundle();
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareTitle);//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareContent);//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);//必填
        ArrayList<String> images = new ArrayList<>();
        images.add(shareImgUrl);
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, images);
        if (mContextReference.get() != null) {
            mTencent = Tencent.createInstance(Constants.QQ_APP_ID, mContextReference.get());
            mTencent.shareToQzone((Activity) mContextReference.get(), params, qqShareListener);
        }
        if (popReference.get() != null) {
            popReference.get().dismiss();
        }
    }

//    public void shareRedbagWyByWXFriend(final String shareTitle, final String shareContent, final String shareUrl,
//                                        String imageUrl, final int flag) {
//        if (TextUtils.isEmpty(shareUrl)) {
//            ToastUtils.show("分享信息未获取到");
//            return;
//        }
//        api = WXAPIFactory.createWXAPI(mContext, Constants.WX_APP_ID, false);
//        api.registerApp(Constants.WX_APP_ID);
//        if (!isWXAppInstalledAndSupported(mContext, api)) {
//            ToastUtils.show("微信客户端未安装，请确认");
//            if (mSharePopWindow != null) {
//                mSharePopWindow.dismiss();
//            }
//            return;
//        }
//        this.shareTitle = shareTitle;
//        this.shareContent = shareContent;
//        this.shareUrl = shareUrl;
//        Handler handler = new Handler() {
//            private Bitmap bmp;
//
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                bmp = (Bitmap) msg.obj;
//                final WXMediaMessage mediaMessage = new WXMediaMessage();
//                if (msg.obj != null) {
//                    bmp = (Bitmap) msg.obj;
//                    if (bmp != null) {
//                        mediaMessage.thumbData = bmpToByteArray(
//                                Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true), true); // 设置缩略图;
//                    }
//                }
//                WXWebpageObject webpage = new WXWebpageObject();
//                webpage.webpageUrl = shareUrl;
//                mediaMessage.mediaObject = webpage;
//                mediaMessage.title = shareTitle;
//                mediaMessage.description = shareContent;
//                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                req.transaction = "urls" + String.valueOf(System.currentTimeMillis());
//                req.message = mediaMessage;
//                req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
//                api.sendReq(req);
//            }
//        };
//        loadingRedbagImage(imageUrl, handler);
//        if (mSharePopWindow != null) {
//            mSharePopWindow.dismiss();
//        }
//    }

    /**
     * 微信分享
     *
     * @param shareTitle   分享的标题
     * @param shareContent 分享的内容
     * @param shareUrl     分享的链接
     * @param imageUrl     分享的图片链接
     * @param flag         0是微信好友，1是微信朋友圈
     */
    public void shareWyByWXFriend(final String shareTitle, final String shareContent, final String shareUrl,
                                  String imageUrl, final int flag) {
        if (TextUtils.isEmpty(shareUrl)) {
            ToastUtils.show("分享信息未获取到");
            return;
        }
        if (mContextReference.get() != null) {
            api = WXAPIFactory.createWXAPI(mContextReference.get(), Constants.WX_APP_ID, false);
            api.registerApp(Constants.WX_APP_ID);
            if (!isWXAppInstalledAndSupported(mContextReference.get(), api)) {
                ToastUtils.show("微信客户端未安装，请确认");
                if (popReference.get() != null) {
                    popReference.get().dismiss();
                }
                return;
            }
            this.shareTitle = shareTitle;
            this.shareContent = shareContent;
            this.shareUrl = shareUrl;
            if (imageUrl.contains("null")){
                imageUrl = "http://7xv1at.com1.z1.glb.clouddn.com/image/logoyoubologo.jpg";
            }

            Handler handler = new Handler() {
                private Bitmap bmp;

                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    bmp = (Bitmap) msg.obj;
                    final WXMediaMessage mediaMessage = new WXMediaMessage();
                    if (msg.obj != null) {
                        bmp = (Bitmap) msg.obj;
                        if (bmp != null) {
                            mediaMessage.thumbData = bmpToByteArray(
                                    Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true), true); // 设置缩略图;
                        }
                    }
                    WXWebpageObject webpage = new WXWebpageObject();
                    webpage.webpageUrl = shareUrl;
                    mediaMessage.mediaObject = webpage;
                    mediaMessage.title = shareTitle;
                    mediaMessage.description = shareContent;
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = "urls" + String.valueOf(System.currentTimeMillis());
                    req.message = mediaMessage;
                    req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                    api.sendReq(req);
                }
            };
            loadingImage(imageUrl, handler);
            if (popReference.get() != null) {
                popReference.get().dismiss();
            }
        }
    }

    /**
     * 微信分享
     *
     * @param shareTitle   分享的标题
     * @param shareContent 分享的内容
     * @param shareUrl     分享的链接
     * @param bmp          分享的图片
     * @param flag         0是微信好友，1是微信朋友圈
     */
    public void shareInvateByWXFriend(final String shareTitle, final String shareContent, final String shareUrl,
                                      Bitmap bmp, final int flag) {
        if (TextUtils.isEmpty(shareUrl)) {
            ToastUtils.show("分享信息未获取到");
            return;
        }
        if (mContextReference.get() != null) {
            api = WXAPIFactory.createWXAPI(mContextReference.get(), Constants.WX_APP_ID, false);
            api.registerApp(Constants.WX_APP_ID);
            if (!isWXAppInstalledAndSupported(mContextReference.get(), api)) {
                ToastUtils.show("微信客户端未安装，请确认");
                if (popReference.get() != null) {
                    popReference.get().dismiss();
                }
                return;
            }
            this.shareTitle = shareTitle;
            this.shareContent = shareContent;
            this.shareUrl = shareUrl;
            // mContext.getResources().getDrawable(R.)

            final WXMediaMessage mediaMessage = new WXMediaMessage();
            if (bmp != null) {
                mediaMessage.thumbData = bmpToByteArray(Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true), true); // 设置缩略图;
            }
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = shareUrl;
            mediaMessage.mediaObject = webpage;
            mediaMessage.title = shareTitle;
            mediaMessage.description = shareContent;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "urls" + String.valueOf(System.currentTimeMillis());
            req.message = mediaMessage;
            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
            api.sendReq(req);
        }
    }

    /**
     * 微信分享图片
     *
     * @param bitmap 图片
     * @param flag   0是微信好友,1是朋友圈
     */
    public void shareInviteImageByWXFriend(Bitmap bitmap, final int flag) {
        if (mContextReference.get() != null) {
            api = WXAPIFactory.createWXAPI(mContextReference.get(), Constants.WX_APP_ID, false);
            api.registerApp(Constants.WX_APP_ID);
            if (!isWXAppInstalledAndSupported(mContextReference.get(), api)) {
                ToastUtils.show("微信客户端未安装，请确认");
                if (popReference.get() != null) {
                    popReference.get().dismiss();
                }
                return;
            }
            WXImageObject imgObj = new WXImageObject(bitmap);
            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imgObj;
            //设置缩略图
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE_WIDTH, THUMB_SIZE_HEIGHT, true);
            bitmap.recycle();
            msg.thumbData = Utils.bmpToByteArray(thumbBmp, true);
            //构造一个REQ
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "urls" + String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
            api.sendReq(req);
        }
    }

    /**
     * 分享微博
     */
    public void shareBySina(String shareTitle, String shareContent, String shareUrl, String imageUrl) {
        Bundle bundle = new Bundle();
        if (imageUrl.contains("null")){
            imageUrl = "http://7xv1at.com1.z1.glb.clouddn.com/image/logoyoubologo.jpg";
        }
        bundle.putString("shareTitle", shareTitle);
        bundle.putString("shareContent", shareContent);
        bundle.putString("shareUrl", shareUrl);
        bundle.putString("imageUrl", imageUrl);
        if (mContextReference.get() != null) {
            Intent intent = new Intent(mContextReference.get(), ShareWeiboActivity.class);
            intent.putExtras(bundle);
            mContextReference.get().startActivity(intent);
            if (popReference.get() != null) {
                popReference.get().dismiss();
            }
        }
    }

    /**
     * 微博分享
     *
     * @param bitmap 分享的图片
     */
    public void shareImageByWeibo(Bitmap bitmap) {
        if (TextUtils.isEmpty(shareUrl) || mContextReference.get() == null) {
            ToastUtils.show("分享信息未获取到");
            return;
        }
        Intent intent = new Intent(mContextReference.get(), ShareWeiboActivity.class);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 100, baos);
        byte[] bitmapByte = baos.toByteArray();
        intent.putExtra("bitmap", bitmapByte);
        mContextReference.get().startActivity(intent);
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (popReference.get() != null) {
            popReference.get().dismiss();
        }
    }

    public IUiListener getQQUIListener(){
        return qqShareListener;
    }

    /**
     * QQ分享
     **/
    public void shareByQQ(String shareTitle, String shareContent, String shareUrl, String imageUrl) {
        if (TextUtils.isEmpty(shareUrl) || mContextReference.get() == null) {
            ToastUtils.show("分享信息未获取到");
            return;
        }
        if (imageUrl.contains("null")){
            imageUrl = "http://7xv1at.com1.z1.glb.clouddn.com/image/logoyoubologo.jpg";
        }
        Bundle bundle = new Bundle();
        bundle.putString("title", shareTitle);
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUrl);
        bundle.putString("targetUrl", shareUrl);
        bundle.putString("summary", shareContent);
        bundle.putString("appName", mContextReference.get().getPackageName());
        L.e("shareByQQ", "URL" + shareUrl);
        mTencent = Tencent.createInstance(Constants.QQ_APP_ID, mContextReference.get());
        mTencent.shareToQQ((Activity) mContextReference.get(), bundle, qqShareListener);
        if (popReference.get() != null) {
            popReference.get().dismiss();
        }
    }

    /**
     * QQ分享
     *
     * @param imageUrl
     */
    public void shareImageByQQ(String imageUrl) {
        if (TextUtils.isEmpty(imageUrl) || mContextReference.get() == null) {
            ToastUtils.show("分享信息未获取到");
            return;
        }
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imageUrl);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        mTencent = Tencent.createInstance(Constants.QQ_APP_ID, mContextReference.get());
        mTencent.shareToQQ((Activity) mContextReference.get(), params, qqShareListener);
        if (popReference.get() != null) {
            popReference.get().dismiss();
        }
    }

    public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void loadingImage(final String imagePath, final Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                URL imageUrl = null;
                InputStream inputStream = null;
                try {
                    imageUrl = new URL(imagePath);
                    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                    // Log.i("imageurl",
                    // "imageurl---"+imagePath+"conn.getResponseCode()"+conn.getResponseCode());
                    if (conn.getResponseCode() == 200) {
                        inputStream = conn.getInputStream();
                        shareDownloadBmp = BitmapFactory.decodeStream(inputStream);
                        msg.obj = shareDownloadBmp;
                        handler.sendMessage(msg);
                    } else {
                        if (mContextReference.get() != null) {
                            shareDownloadBmp = BitmapFactory.decodeResource(mContextReference.get().getResources(), R.drawable.default_img);
                            msg.obj = shareDownloadBmp;
                            handler.sendMessage(msg);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    // Log.i("imageurl", "imageurl---"+e.getMessage());
                    if (mContextReference.get() != null) {
                        shareDownloadBmp = BitmapFactory.decodeResource(mContextReference.get().getResources(), R.mipmap.ic_launcher);
                        msg.obj = shareDownloadBmp;
                        handler.sendMessage(msg);
                    }
                } finally {
                    CloseUtil.close(inputStream);
                }
            }
        }).start();
    }


    @Override
    public void onSuccess(JSONObject object, String method) {
        //具体业务子类实现
        L.e("params", "params : " + object.toString());
        if (object.has("extend")) {
            try {
                String extendStr = object.getString("extend");
                showTaskCoins(extendStr);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String errMsg, String method) {
        ToastUtils.show("请求错误");
    }

    @Override
    public void onFaild(JSONObject object, String method) {
        if (object.has("result")) {
            try {
                ToastUtils.show(object.getString("result"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void showTaskCoins(String extendStr) {
        if (!TextUtils.isEmpty(extendStr) && (!extendStr.equals("{}"))) {
            try {
                JSONObject jsonObj = new JSONObject(extendStr);
                ArrayList<CompleteTask> tasks = new Gson().fromJson(jsonObj.getString("completeTasks"),
                        new TypeToken<List<CompleteTask>>() {
                        }.getType());
                if (tasks != null) {
                    for (int i = 0; i < tasks.size(); i++) {
                        CompleteTask currentTask = tasks.get(i);
                        int type = currentTask.getTaskType();
                        int currentTaskIdentify = currentTask.getTaskIdentify();
                        if (type == 1) {
                            switch (currentTaskIdentify) {
                                case Constants.SHARE:
                                    showCoinToast("分享     +" + currentTask.getCoin() + "金币");
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void showCoinToast(String msg) {
        if (mContextReference.get()!=null) {
            Toast toast = Toast.makeText(mContextReference.get(), msg, Toast.LENGTH_SHORT);
            LinearLayout toastView = (LinearLayout) toast.getView();
            ImageView imageCodeProject = new ImageView(mContextReference.get());
            imageCodeProject.setImageResource(R.drawable.coin_icon);
            toastView.addView(imageCodeProject, 0);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }
}

